package com.panopset.gui;

import java.awt.Color;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

import com.panopset.Strings;
import com.panopset.gui.container.TitledPanel;
import com.panopset.swing.App;
import com.panopset.swing.FontManager;
import com.panopset.swing.FontManager.FontType;

/**
 * Data entry.
 */
public class ValidatingDataEntry {
	
	public final PVEID id;

    /**
     * Text field.
     */
    public final TTextField tf = new TTextField();

    /**
     * @return Text value.
     */
    public final String getValue() {
        return tf.getText();
    }

    /**
     * Set value.
     * 
     * @param val
     *            Value to set.
     */
    public void setValue(final String val) {
        tf.setText(val);
        tf.invalidate();
        updateGui();
        App.app.f.getFrame().validate();
    }

    /**
     * Panel.
     */
    private final TitledPanel p;

    /**
     * @return Titled panel.
     */
    public TitledPanel getTitledPanel() {
        return p;
    }

    /**
     * @param namedValue
     *            Named value.
     */
    ValidatingDataEntry(final PVEID pveId) {
    	id = pveId;
        p = new TitledPanel(id.getTip(), new GridBagLayout(), id.getTip());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.anchor = GridBagConstraints.WEST;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.weightx = 1.0;
        p.getPanel().add(tf, gbc);
        FontManager.register(tf, FontType.monospace);
        tf.setToolTipText(id.getTip());
        tf.addKeyListener(new KeyAdapter() {

            @Override
            public void keyReleased(final KeyEvent e) {
                ValidatingDataEntry.this.updateGui();
            }
        });
    }
    
    public boolean validate(final String s) {
    	return true;
    }

    /**
     * Update.
     */
    public void updateGui() {
        String s = tf.getText();
        if (Strings.isPopulated(s)) {
            if (validate(s)) {
                getTitledPanel().setNormalHighlighting();
                tf.setBackground(Color.WHITE);
            } else {
                tf.setBackground(Color.RED);
                getTitledPanel().setAlertHighlighting();
            }
        } else {
            getTitledPanel().setAlertHighlighting();
            tf.setBackground(Color.YELLOW);
        }
        UtilGUI.updateComponent(getTitledPanel().getPanel());
    }
}

